package com.sg;

import android.app.ActivityManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Process;
import android.text.TextUtils;
import android.util.Log;


import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import com.huawei.hms.aaid.HmsInstanceId;
import com.huawei.hms.common.ApiException;
import com.sg.utils.RomUtil;
import com.xiaomi.mipush.sdk.MiPushClient;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class IPushHelper {
    public static final String TAG = "IPushHelper";
    private String hwAppId, xmAppId, xmAppKey;
    public String xmRegId, hwToken;
    public ReactApplicationContext reactApplicationContext;
    private Context context;
    private static volatile IPushHelper instance = null;

    private IPushHelper() {


    }

    public static IPushHelper getInstance() {
        synchronized (IPushHelper.class) {
            if (instance == null) {

                instance = new IPushHelper();
            }
            return instance;
        }
    }






    public IPushHelper setContext(Context context) {
        this.context = context;
        BroadcastReceiver mb = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String s = intent.getAction();
                String data = intent.getStringExtra("data");
                reactApplicationContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                        .emit("onNotificationMessageArrived", data);
            }
        };
        IntentFilter mif = new IntentFilter("ipush.onNotificationMessageArrived");
        context.registerReceiver(mb, mif);

        BroadcastReceiver mb2 = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String s = intent.getAction();
                String data = intent.getStringExtra("data");
                reactApplicationContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                        .emit("onNotificationMessageClicked", data);
            }
        };
        IntentFilter mif2 = new IntentFilter("ipush.onNotificationMessageClicked");
        context.registerReceiver(mb2, mif2);
        return this;
    }





    public IPushHelper setHuawei(String appid) {
        this.hwAppId = appid;
        return this;
    }

    public IPushHelper setXiaomi(String appid, String appkey) {
        this.xmAppId = appid;
        this.xmAppKey = appkey;
        if (RomUtil.isMiui() && shouldInit()) {
            MiPushClient.registerPush(this.context, appid, appkey);
        }
        return this;
    }

    private boolean shouldInit() {
        if (this.context == null) {
            System.out.print("[sg]:context is null");
            throw new NullPointerException();
        }

        ActivityManager am = ((ActivityManager) this.context.getSystemService(Context.ACTIVITY_SERVICE));
        List<ActivityManager.RunningAppProcessInfo> processInfos = am.getRunningAppProcesses();
        String mainProcessName = this.context.getApplicationInfo().processName;
        int myPid = Process.myPid();
        for (ActivityManager.RunningAppProcessInfo info : processInfos) {
            if (info.pid == myPid && mainProcessName.equals(info.processName)) {
                return true;
            }
        }
        return false;
    }


    public interface Callback {
        void onSuccess(String s);

        void onFailure(String errMsg);
    }

    public String getHwToken() {
        if (this.context == null) {
            System.out.print("[sg]:context is null");
            throw new NullPointerException();
        }
        if (!TextUtils.isEmpty(this.hwToken)) return this.hwToken;
        try {
            String token = HmsInstanceId.getInstance(this.context.getApplicationContext()).getToken(this.hwAppId, "HCM");
            this.hwToken = token;
            return token;
        } catch (ApiException e) {
            e.printStackTrace();
            Log.e(TAG, e.toString());
        }
        return "";
    }

    public String getXmRegId() {
        if (!TextUtils.isEmpty(this.xmRegId)) return this.xmRegId;
        String regId = MiPushClient.getRegId(reactApplicationContext);
        this.xmRegId = regId;
        return regId;
    }


    /**
     * hw：自定义点击消息动作
     * 打开应用首页并携带数据给应用
     * 为了确保在跳转的页面获取到传输的数据，请在“onNewIntent”方法中调用“setIntent”方法更新intent为跳转页面时传入的intent，并在“onCreate”和“onNewIntent”方法中调用同一个处理数据的方法（本文中以getIntentData方法为例）。
     * @param intent
     */
    public void getIntentData(Intent intent) {
        if (null != intent) {
            // 获取data里的值
            Bundle bundle = intent.getExtras();
            if (bundle != null) {
                HashMap<String, Object> hashMap = new HashMap<>();
                for (String key : bundle.keySet()) {
                    String content = bundle.getString(key);
                    hashMap.put(key,content);
//                    Log.i(TAG, "receive data from push, key = " + key + ", content = " + content);
                }
                Log.i(TAG,hashMap.toString());
                reactApplicationContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
                        .emit("onNotificationMessageClicked", new JSONObject(hashMap).toString());
            }

        } else {
            Log.i(TAG, "intent is null");
        }


    }
}
